<?php

/**
 * 用户控制器
 */

namespace app\admin\controller;

use app\common\model\Adjust;
use Exception;
use think\Request;
use think\response\Json;
use app\common\model\User;
use app\common\model\UserLevel;

use app\common\validate\UserValidate;
use think\facade\Db;
use think\facade\Log;
use util\geetest\GeeTest;

class UserController extends AdminBaseController
{

    /**
     * 列表
     * @param Request $request
     * @param User $model
     * @return string
     * @throws Exception
     */
    public function index(Request $request, User $model): string
    {
        $param = $request->param();
        if (!isset($param['start_time'])) {
            $param['start_time'] = date('Y-m-d') . ' 00:00:00';
            $param['end_time'] = date('Y-m-d') . ' 23:59:59';
        } else {
            $param['start_time'] = $param['start_time'] . ' 00:00:00';
            $param['end_time'] = $param['end_time'] . ' 23:59:59';
        }
        $model = $model->whereBetweenTime('create_time', $param['start_time'], $param['end_time']);
        if (isset($param['_keywords']) && $param['_keywords'] != '') {
            $model = $model->whereLike('usercode|adid|mobile', "%{$param['_keywords']}%");
        }
        $data  = $model->order('id desc')
            ->paginate([
                'list_rows' => $this->admin['admin_list_rows'],
                'var_page'  => 'page',
                'query'     => $request->get(),
            ]);
        // 关键词，排序等赋值
        $this->assign($request->get());
        foreach ($data as $da) {
            if ($da['mobile'] && $da['adid']) {
                $adjust_arr = Adjust::where('adid', $da['adid'])->find();
                $da['mobile'] = $adjust_arr['country'] . '--' . $da['mobile'];
            }
        }

        $this->assign([
            'data'            => $data,
            'page'            => $data->render(),
            'total'           => $data->total(),
            'user_level_list' => UserLevel::select(),
            'status_list'     => User::STATUS_LIST,
        ]);
        // print_R($data);die;
        return $this->fetch();
    }

    /**
     * 添加
     *
     * @param Request $request
     * @param User $model
     * @param UserValidate $validate
     * @return string|Json
     * @throws Exception
     */
    public function add(Request $request, User $model, UserValidate $validate)
    {
        if ($request->isPost()) {
            $param           = $request->param();
            $validate_result = $validate->scene('admin_add')->check($param);
            if (!$validate_result) {
                return admin_error($validate->getError());
            }

            $result = $model::create($param);

            $url = URL_BACK;
            if (isset($param['_create']) && (int)$param['_create'] === 1) {
                $url = URL_RELOAD;
            }
            return $result ? admin_success('添加成功', [], $url) : admin_error();
        }
        $this->assign([
            'user_level_list' => UserLevel::select(),

        ]);


        return $this->fetch();
    }

    /**
     * 修改
     *
     * @param $id
     * @param Request $request
     * @param User $model
     * @param UserValidate $validate
     * @return string|Json
     * @throws Exception
     */
    public function edit($id, Request $request, User $model, UserValidate $validate)
    {
        $data = $model->findOrEmpty($id);
        if ($request->isPost()) {
            $param = $request->param();
            $check = $validate->scene('admin_edit')->check($param);
            if (!$check) {
                return admin_error($validate->getError());
            }

            $result = $data->save($param);

            return $result ? admin_success('修改成功', [], URL_BACK) : admin_error('修改失败');
        }

        $this->assign([
            'data'            => $data,
            'user_level_list' => UserLevel::select(),

        ]);

        return $this->fetch('add');
    }

    /**
     * 删除
     *
     * @param mixed $id
     * @param User $model
     * @return Json
     */
    public function del($id, User $model): Json
    {
        $check = $model->inNoDeletionIds($id);
        if (false !== $check) {
            return admin_error('ID为' . $check . '的数据不能被删除');
        }

        $result = $model::destroy(static function ($query) use ($id) {
            /** @var \think\db\Query $query */
            $query->whereIn('id', $id);
        });

        return $result ? admin_success('删除成功', [], URL_RELOAD) : admin_error('删除失败');
    }

    /**
     * 启用
     * @param mixed $id
     * @param User $model
     * @return Json
     */
    public function enable($id, User $model): Json
    {

        $result = $model->whereIn('id', $id)->update(['status' => 1]);
        return $result ? admin_success('操作成功', [], URL_RELOAD) : admin_error();
    }

    /**
     * 禁用
     * @param mixed $id
     * @param User $model
     * @return Json
     */
    public function disable($id, User $model): Json
    {
        $result = $model->whereIn('id', $id)->update(['status' => 0]);
        return $result ? admin_success('操作成功', [], URL_RELOAD) : admin_error();
    }

    /**
     * 导入
     * @param Request $request
     * @return Json
     */
    public function import(Request $request)
    {
        $param           = $request->param();
        $field_name_list = ['手机号'];
        if (isset($param['action']) && $param['action'] === 'download_example') {
            $this->downloadExample($field_name_list);
        }

        $field_list = ['mobile'];
        $result     = $this->result_import('file', 'user', $field_list);
        if ($result) {
            foreach ($result as $k => $v) {

                $mobile = $v[0];
                if ($mobile) {
                    $user_arr = User::where('mobile', $mobile)->find();
                    if ($user_arr && $user_arr['adid'] != '') {
                        $in_arr = [
                            'appid' => $user_arr['appcode'],
                            'mobile' => $user_arr['mobile'],
                            'adid' => $user_arr['adid'],
                            'status' => 2,
                            'create_time' => date('Y-m-d H:i:s')
                        ];
                    } else {
                        $in_arr = [
                            // 'appid'=>$param['appid'],
                            'mobile' => $mobile,
                            // 'adid'=>$param['adid'],
                            'status' => 0,
                            'create_time' => date('Y-m-d H:i:s')
                        ];
                    }
                    Db::table('import_adjust')->insert($in_arr);
                }

                // $params['s2s'] = 1;
                // $params['adid'] = $v['adid'];
                // $params['event_token'] = 'wwjc4d'; //'2402932684aee494739abe9c7c1f2f04';
                // $params['app_token'] = 'o2bh132j6eio';
                // $params['callback_params'] = json_encode(['mobile' => $v['mobile']]);
                // $data = http_post('https://s2s.adjust.com/event', $params, true);
                // Log::write('adjust-s2s 手机号：' . $v['mobile'] . '返回' . $data, 'info');
            }
        }
        return json(['code' => 0, 'msg' => '上传成功.' . count($result)]);
    }

    /**
     * 导出
     * @param Request $request
     * @param User $model
     * @throws Exception
     */
    public function export(Request $request, User $model): void
    {
        $param = $request->param();
        $data  = $model->with('user_level')->scope('where', $param)->select();

        $header = ['ID',  '手机号', '创建时间', 'adid', 'usercode'];
        $body   = [];
        foreach ($data as $item) {
            if ($item->mobile != '') {
                $record                  = [];
                $record['id']            = $item->id;
                $record['mobile']        = $item->mobile;
                $record['create_time']   = $item->create_time;
                $record['adid'] = $item->adid ?? '';
                $record['usercode']      = $item->usercode;

                $body[] = $record;
            }
        }
        $this->exportData($header, $body, '用户数据-' . date('YmdHis'));
    }
}
